package com.cop4331.social;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.color;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Displays list of tutors to the user for them to select
 * 
 */
public class ChooseTutorActivity extends Activity {

	String cname;
	String term = "";
	
	TextView choosenUser;
	View tempView = null;
	
	Button ok;
	Button cancel;
	
	static String tutor = "";
	final String IP = UserFunctions.getIp();

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.choosetutor);

		// TextView
		choosenUser = (TextView) findViewById(R.id.tv_select); // Shows which
																// user has been
																// selected to
																// user

		// Buttons
		ok = (Button) findViewById(R.id.b_ok);
		cancel = (Button) findViewById(R.id.b_cancel);

		// Button is originally disabled until a user has been selected.
		ok.setEnabled(false);

		// Get class name from previous activity (NeedTutorActivity)
		Bundle b = getIntent().getExtras();
		cname = b.getString("cname");

		// Retreive current term from SQLite Database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		term = user.get("uid");
		String un = user.get("name");

		// Attach listview to listview in choosetutorlist.xml
		ListView lv = (ListView) findViewById(R.id.list);
		Parcelable state = lv.onSaveInstanceState();

		try {

			// Set adapter
			// Adapter comes from SimpleAdapter_Ext Class
			/*
			 * List Contains: Username Fullname Grade Image Url String
			 */
			lv.setAdapter(new SimpleAdapter_Ext(this, getData(),
					R.layout.choosetutorlistview, new String[] { "un", "full",
							"grade", "img" }, new int[] { R.id.text, R.id.full,
							R.id.grade, R.id.img }));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Restore previous state (including selected item index and scroll
		// position)
		lv.onRestoreInstanceState(state);

		// Give the listview functionality when a user clicks it
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {

				// A new item is selected, default the old selected item
				// background color
				if (tempView != null) {
					tempView.setBackgroundColor(Color.BLACK);
				}

				// We have selected an item, enable the continue button
				ok.setEnabled(true);

				// Change the current selected item background color
				// This allows us to show which item has been selected.
				view.setBackgroundColor(Color.DKGRAY);

				// Retreive the current selected item details
				final Map<String, Object> item = (Map<String, Object>) parent
						.getItemAtPosition(pos);

				final Dialog dialog = new Dialog(ChooseTutorActivity.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.viewprofiledialog);
				dialog.setCancelable(false);
				
				// Display User profile Dialog--------------------------------
				
				//Configure RatingBar
				final RatingBar rating = (RatingBar) dialog
						.findViewById(R.id.rating);
				
				// Configure Profile Image
				ImageView pic = (ImageView) dialog
						.findViewById(R.id.profilepic);
				
				// TextViews
				TextView name = (TextView) dialog.findViewById(R.id.name);
				TextView phone = (TextView) dialog.findViewById(R.id.phone);
				TextView email = (TextView) dialog.findViewById(R.id.email);
				TextView major = (TextView) dialog.findViewById(R.id.major);
				TextView cnt = (TextView) dialog.findViewById(R.id.count);
				
				// Buttons
				Button close = (Button) dialog.findViewById(R.id.close);
				Button message = (Button) dialog.findViewById(R.id.message);

				rating.setRating((float) Double.parseDouble((String) item
						.get("rating")));
				Button ok = (Button) dialog.findViewById(R.id.ok);
				
				// Set User Info to Display
				name.setText((String) item.get("full"));
				email.setText((String) item.get("email"));
				major.setText((String) item.get("major"));
				phone.setText((String) item.get("phone"));
				cnt.setText("Out of " + (String) item.get("numRatings")
						+ " rating(s)");

				// Display User Profile Image
				Drawable drawable;

				try {
					drawable = grabImageFromUrl((String) item.get("img"));
					pic.setImageDrawable(drawable);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				// Enable Close Dialog Button
				close.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();
					}

				});
				
				// Enable Message User Button
				message.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						// Bundle the selected tutor for the
						// ReplyMessagetActivity (We will add to the database
						// in the next frame)
						Bundle b = new Bundle();
						b.putString("sender", (String) item.get("un"));
						b.putString("subject", "null");

						// Goto the ReplyMessageActivity
						Intent log = new Intent(getApplicationContext(),
								ReplyMessageActivity.class);
						log.putExtras(b);
						startActivity(log);

					}
				});

				dialog.setCanceledOnTouchOutside(true);
				dialog.show();

				// The tempView is equal to the current view here, the next
				// iteration, tempView is equal to the previous view and so
				// forth
				tempView = view;

				// Retreive username from the selected item and display to user
				// in TextView
				tutor = (String) item.get("un");
				choosenUser.setTextKeepState("You have chosen "
						+ (String) item.get("full")
						+ " as a tutor.\nPress ok to continue.");
				choosenUser.setGravity(Gravity.CENTER_HORIZONTAL);
			}
		});

		// Gives functionality to "OK" Button
		ok.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Bundle the selected tutor for the ScheduleRequestActivity (We
				// will add to the database in the next frame)
				Bundle b = new Bundle();
				b.putString("tutor", tutor);
				b.putString("cname", cname);

				// Goto the ScheduleRequestActivity
				Intent log = new Intent(getApplicationContext(),
						ScheduleRequestActivity.class);
				log.putExtras(b);
				startActivity(log);
				finish();

			}
		});

		// Gives functionality to the "CANCEL" Button
		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Return to dashboard
				Intent log = new Intent(getApplicationContext(),
						NeedTutorActivity.class);
				startActivity(log);
				finish();

			}
		});
		
		// Title Bar Features
		ImageButton about, home, message;

		about = (ImageButton) findViewById(R.id.b_about);
		home = (ImageButton) findViewById(R.id.b_home);
		message = (ImageButton) findViewById(R.id.b_message);

		UserFunctions uf = new UserFunctions();
		
		// Check for new messages, display button if new message
		JSONObject j_mess = uf.retreiveMessages(un, "new");

		try {
			if (Integer.parseInt(j_mess.getString("size")) > 0) {
				message.setVisibility(View.VISIBLE);
			} else
				message.setVisibility(View.GONE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		// Display App Info
		about.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(ChooseTutorActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("CramSessions v 1.0 2012");
				dialog.setCancelable(true);

				// Create and show a dialog to help the user with this specific
				// field
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("CramSessions was created by:\n\n-Matt Szoke\n-Daniel Moody\n-Jeovanny Alvarez\n-Kia Manoochehri\n-Rj Anderson\n-Doug Wagner");
				text.setGravity(Gravity.LEFT);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});
		
		// Return Home Button
		home.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		// Goto Inbox button (only if new message found)
		message.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(sa);
				finish();

			}
		});
	}

	// -----------------------------------------------
	// GETDATA
	// Retreives and returns list of available tutors from the database
	// -----------------------------------------------
	private List<Map<String, Object>> getData() throws Exception {

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // Used
																				// to
																				// store
																				// the
																				// available
																				// tutors
																				// from
																				// Database

		// Retreive tutors
		UserFunctions uf = new UserFunctions();
		JSONObject json = uf.retrieveTutors(cname, term);

		// Stores size of the list returned from Database
		int size;

		try {

			size = Integer.parseInt(json.getString("size"));

			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					JSONObject json_course = json.getJSONObject("" + i);

					// Retreive current user information from the database
					JSONObject json_user = uf.userExists(
							json_course.getString("username")).getJSONObject(
							"user");

					// Place each object in the HashMap
					map.put("un", json_course.getString("username"));
					map.put("full", json_user.getString("full"));
					map.put("grade", json_course.getString("grade"));
					map.put("major", json_user.getString("major"));
					map.put("phone", json_user.getString("phone"));
					map.put("email", json_user.getString("email"));
					map.put("rating", json_user.getString("rating"));
					map.put("numRatings", json_user.getString("numRatings"));

					// Different URLS: 97.104.23.63 from a outside machien,
					// 192.168.1.53 from a home machine
					String URLstring = IP + "profilepictures/"
							+ json_user.getString("img");
					// String URLstring =
					// "http://192.168.1.53/android/profilepictures/" +
					// json_user.getString("img");

					map.put("img", URLstring);
					list.add(map);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return list;
	}

	private Drawable grabImageFromUrl(String url) throws Exception {
		return Drawable.createFromStream(
				(InputStream) new URL(url).getContent(), "src");
	}
}
